import { ref, reactive, computed } from 'vue'
import { defineStore } from 'pinia'

import {doLoginAPI} from "@/api/user.js";

export const useUserStore = defineStore('user', () => {
    const userInfo = reactive({
        token: "",
        userid: "",
    })

    const token = computed(() => {
        return userInfo.token;
    })
    const userid = computed(() => {
        return userInfo.userid;
    })
    const isLogin = computed(() => {
        return !!(userInfo.token && userInfo.userid);
    })

    const updateAuthority = (payload) => {
        // userInfo.token = payload.token;
        // userInfo.userid = payload.userid;
        for (var key in payload) {
            if (Object.hasOwn(userInfo, key)) {
                userInfo[key] = payload[key];
            }
        }
    }

    const loginAndUpdateAuthority = async (payload) => {
        return doLoginAPI(payload).then(res=>{
            console.log("登陆成功",res);
            updateAuthority(res.data);
        })
    }

    const existAndUpdateAuthority = ()=>{
        updateAuthority({token:"",userid:""});
    }


    return {
        userInfo,
        token,
        userid,
        isLogin,
        updateAuthority,
        loginAndUpdateAuthority,
        existAndUpdateAuthority
    }
},{
    persist:true,
    // persist:{
    //     key:"laowang",  // key
    //     storage: sessionStorage,
    //     paths:["userInfo.token"]
    // }
})
